package com.czy.owner.ui.archive;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.api.CarParameterSetApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.ActionSheetDialog;
import com.iflytek.thirdparty.P;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by King on 2017-05-17
 * 车辆参数
 */

public class CarParameterActivity extends BaseActivity {
    @BindView(R.id.et_parameter_gearbox)
    EditText etGearbox;
//    @BindView(R.id.et_parameter_engine)
//    EditText etEngine;
    @BindView(R.id.tv_parameter_antifreeze)
    TextView tvAntifreeze;
    @BindView(R.id.et_parameter_tyre)
    EditText etTyre;
    @BindView(R.id.et_parameter_wiper)
    EditText etWiper;
    @BindView(R.id.tv_year_check_time)
    TextView tvYearCheckTime;
    @BindView(R.id.btn_car_parameter_submit)
    Button btnSubmit;

    private String[] colorArray = {"红色","绿色"};
    private ActionSheetDialog.SheetItemColor[] sheetColorArray  = new ActionSheetDialog.SheetItemColor[2];
    private CarInfo mCarInfo;
    private int currentYear, currentMonth, currentDay;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_car_parameter;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(this, "参数异常!");
            finish();
            return;
        }
        getToolbarTitle().setText("车辆参数");
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR)+10;
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void updateViews() {
        /**
         * "engineModel": "发动机型号",
         "wiperType": "雨刮器类型",
         "tireSpec": "轮胎规格",
         "antifreezeColor": 防冻液颜色 ,
         "transmissionType": "变速箱类型",
        **/
        etGearbox.setText(mCarInfo.getTransmissionType());
//        etEngine.setText(mCarInfo.getEngineModel());
        tvAntifreeze.setText(mCarInfo.getAntifreezeColor());
        etTyre.setText(mCarInfo.getTireSpec());
        etWiper.setText(mCarInfo.getWiperType());
        MyLog.e("yang","mCarInfo.getNextInspectionTime()=="+mCarInfo.getNextInspectionTime());
        if(mCarInfo.getNextInspectionTime()!=0){
            tvYearCheckTime.setText(TimeUtils.formatTimeDifference3(mCarInfo.getNextInspectionTime())+"");
        }

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CarParameterSetApi carParameterSetApi = new CarParameterSetApi(new HttpOnNextListener<String>() {
                    @Override
                    public void onNext(String o) {
                        Toast.makeText(CarParameterActivity.this, "车辆参数修改成功!", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        Toast.makeText(CarParameterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                },CarParameterActivity.this);



                HashMap<String,Object> requestMap = new HashMap<>();
                requestMap.put("session", UserHelper.getInstance().getSessionInfoModel(CarParameterActivity.this).getSession());
                requestMap.put("ownerCarId",mCarInfo.getOwnerCarId());
//                requestMap.put("engineModel",etEngine.getText().toString().trim());
                requestMap.put("transmissionType",etGearbox.getText().toString().trim());
                requestMap.put("antifreezeColor",tvAntifreeze.getText().toString().trim());
                requestMap.put("tireSpec",etTyre.getText().toString().trim());
                requestMap.put("wiperType",etWiper.getText().toString().trim());
                requestMap.put("nextInspectionTime",TimeUtils.getTimeStamp(tvYearCheckTime.getText().toString().trim(),"yyyy-MM-dd"));
                carParameterSetApi.setMap(requestMap);
                HttpManager.getInstance().doHttpDeal(carParameterSetApi);
            }
        });
    }

    private void showAntifreezeDialog(){
        String antifreezeColor = tvAntifreeze.getText().toString().trim();
        sheetColorArray[0] = ActionSheetDialog.SheetItemColor.Gray;
        sheetColorArray[1] = ActionSheetDialog.SheetItemColor.Gray;
        if(!TextUtils.isEmpty(antifreezeColor)){
            if(antifreezeColor.equals(colorArray[0])){
                sheetColorArray[0] = ActionSheetDialog.SheetItemColor.ThemeColor;
            }
            if(antifreezeColor.equals(colorArray[1])){
                sheetColorArray[1] = ActionSheetDialog.SheetItemColor.ThemeColor;
            }
        }
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true)
                .addSheetItem(colorArray[0], sheetColorArray[0],
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                tvAntifreeze.setText(colorArray[0]);
                            }
                        })
                .addSheetItem(colorArray[1], sheetColorArray[1],
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                tvAntifreeze.setText(colorArray[1]);
                            }
                        }).show();
    }

    @OnClick({R.id.ll_year_check_time,R.id.tv_parameter_antifreeze})
    public void MyOnClick(View view){
        switch (view.getId()){
            case R.id.ll_year_check_time:
                showDateDialog();
                break;
            case  R.id.tv_parameter_antifreeze:
                showAntifreezeDialog();
                break;
        }
    }


    private void showDateDialog() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        if (!TextUtils.isEmpty(tvYearCheckTime.getText())) {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(tvYearCheckTime.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(date !=null){
                tmpCalendar.setTime(date);
            }
        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mDateDialog = new Dialog(CarParameterActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(CarParameterActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择时间");
        final WheelView wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        final WheelView wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        final WheelView wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);


        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(CarParameterActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(CarParameterActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""),
                        txtMonth = "0" + (wvMonth.getCurrentItem() + 1),
                        txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);
                MyLog.e("yang","/////////=="+TimeUtils.getTimeStamp((txtYear + "-" + txtMonth + "-" + txtDay+" 59:59:59"),"yyyy-MM-dd HH:mm:ss"));
                MyLog.e("yang","*******=="+System.currentTimeMillis());
                if(TimeUtils.getTimeStamp((txtYear + "-" + txtMonth + "-" + txtDay+" 59:59:59"),"yyyy-MM-dd HH:mm:ss")>=System.currentTimeMillis()){
                    tvYearCheckTime.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                    mDateDialog.dismiss();
                }else {
                    PhoneUtils.ShowToastMessage(CarParameterActivity.this,"年检日期应大于等于当前日期");
                }

            }
        });

        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }

    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }



}
